package org.example.aspect;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.annotation.Auth;
import org.example.utils.JwtUtils;
import org.example.constant.MessageConstant;
import org.example.enums.AuthEnum;
import org.example.exception.AuthException;
import org.example.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@Component
@Slf4j
public class AuthAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserRoleService userRoleService;

    @Pointcut("@annotation(org.example.annotation.Auth)")
    public void authCutPoint() {
    }


    @Before("authCutPoint()")
    public void authPoint(JoinPoint joinPoint) {
        AtomicInteger flag = new AtomicInteger();
        JSONObject token = JwtUtils.of(request.getHeader("token"));
        String id = token.get("id").toString();
        String role = userRoleService.queryRoleByUserId(id);
        //获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Auth annotation = signature.getMethod().getAnnotation(Auth.class);
        //获取注解的value值
        AuthEnum[] value = annotation.value();
        Arrays.stream(value).forEach(m -> {
            if (Objects.equals(role, m.toString())) {
                flag.set(1);
            }
        });
        if (flag.intValue() != 1) {
            throw new AuthException(MessageConstant.AUTH_ERROR);
        }
    }
}
